package com.gogowan.agroenterprise.newview;

import java.lang.reflect.Type;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.JksSHA1Fingerprint;
import com.gogowan.agroenterprise.LoginActivity;
import com.gogowan.agroenterprise.MyApplication;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.SpectorActivity;
import com.gogowan.agroenterprise.UpdateActivity;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.Enum.Temp;
import com.gogowan.agroenterprise.contorl.HttpConnectService;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.AsyncLoadListener;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.InterActionModel;
import com.gogowan.agroenterprise.db.DBHelper;
import com.gogowan.agroenterprise.model.BoxBindCodeRequest;
import com.gogowan.agroenterprise.model.BoxBindCodeResult;
import com.gogowan.agroenterprise.model.CodeActivationInfo;
import com.gogowan.agroenterprise.model.CodeActivationResultInfo;
import com.gogowan.agroenterprise.model.GetbaseInfoRequest;
import com.gogowan.agroenterprise.model.GetbaseInfoResult;
import com.gogowan.agroenterprise.model.MaterialBatch;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.OperationTypeDict;
import com.gogowan.agroenterprise.model.SplitBoxGetCodeRequest;
import com.gogowan.agroenterprise.model.SplitBoxGetCodeResult;
import com.gogowan.agroenterprise.model.UserType;
import com.gogowan.agroenterprise.model.Version;
import com.gogowan.agroenterprise.model.VersionClientInfo;
import com.gogowan.agroenterprise.newview.NewCollectSelect.DataSyncTask;
import com.gogowan.agroenterprise.storage.CribActivity;
import com.gogowan.agroenterprise.storage.DealerListActivity;
import com.gogowan.agroenterprise.storage.HistoryActivity;
import com.gogowan.agroenterprise.storage.InStorageActivity;
import com.gogowan.agroenterprise.storage.InventoryActivity;
import com.gogowan.agroenterprise.storage.OutStorageActivity;
import com.gogowan.agroenterprise.storage.PackActivity;
import com.gogowan.agroenterprise.storage.UnpackActivity;
import com.gogowan.agroenterprise.storage.WarehouseListActivity;
import com.gogowan.agroenterprise.utils.PalUtils;
import com.gogowan.agroenterprise.utils.PermissionUtil;
import com.gogowan.agroenterprise.utils.PopupWindowUtil;
import com.gogowan.agroenterprise.utils.Utils;
import com.gogowan.agroenterprise.widget.xlistview.WorkStateBean;
import com.google.gson.reflect.TypeToken;
import com.hp.hpl.sparta.Document.Index;
import com.ioid.utils.JsonUtils;
import com.ioid.utils.StringUtils;
import com.lidroid.xutils.exception.HttpException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import u.aly.V;

public class NewMainActivity extends BaseActivity implements AsyncLoadListener,OnClickListener {

	private RelativeLayout operation;
	private RelativeLayout spector;
	private RelativeLayout sales;
	private PopupWindow setPop;
	private ImageButton setBtn;
	// private Button activate;
	// private Button supplyAndDemand;
	private TextView exit;
	// private TextView op, spec, sale, active, sad, exittext;
	// private TextPaint tp;
	private boolean isNew;
	private ProgressDialog progressDialog;
	private long enterpriseId;

	// added on 20170109
	private WeakRefAsyncTask weakRefAsyncTask = new WeakRefAsyncTask(this);
	private static final int BOX_RQT = 1;
	private static final int GIFT_RQT = 2;
	private static final int UNPACK_RQT = 3;
	private static final int BOX_RQC = 199301;
	private static final int GIFT_RQC = 199302;
	private static final int UNPACK_RQC = 199303;
	private static final int CRIB_RQC = 199304;
	private String scanCode = "";
	private DBHelper dbHelper;
	private PermissionUtil permissionUtil;
	/** Called when the activity is first created. */
	@SuppressLint("MissingInflatedId")
    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.new_main_activity);

		dbHelper = new DBHelper(this);
		dbHelper.openDatabase();
		operation = (RelativeLayout) findViewById(R.id.main_rl_operation);
		spector = (RelativeLayout) findViewById(R.id.main_rl_spector);
		sales = (RelativeLayout) findViewById(R.id.main_rl_sales);
		exit = (TextView) findViewById(R.id.main_btn_exit);

		// op = (TextView) findViewById(R.id.main_txt_op);
		// tp = op.getPaint();
		// tp.setFakeBoldText(true);
		// spec = (TextView) findViewById(R.id.main_txt_spec);
		// tp = spec.getPaint();
		// tp.setFakeBoldText(true);
		// sale = (TextView) findViewById(R.id.main_txt_sale);
		// tp = sale.getPaint();
		// tp.setFakeBoldText(true);
		// active = (TextView) findViewById(R.id.main_txt_activate);
		// tp = active.getPaint();
		// tp.setFakeBoldText(true);
		// sad = (TextView) findViewById(R.id.main_txt_sd);
		// tp = sad.getPaint();
		// tp.setFakeBoldText(true);
		// exittext = (TextView) findViewById(R.id.main_txt_exit);
		// tp = exittext.getPaint();
		// tp.setFakeBoldText(true);
		deleteMoreLogs();
		// 版本更新
		UpdateAsync updateAsync = new UpdateAsync();
		updateAsync.execute();
		permissionUtil=new PermissionUtil(this);
		isNew = MyApplication.mSettings.getBoolean("isNew", false);
		enterpriseId =  MyApplication.mSettings.getLong("enterpriseid", 0);
		if (MyApplication.mSettings.getInt("usertype",0)== UserType._JING_XIAO_SHANG.getTypeID()){
			//经销商
			findViewById(R.id.ll1).setVisibility(View.GONE);
			findViewById(R.id.ll_gongchang).setVisibility(View.GONE);
			findViewById(R.id.ll_jingxiangshang).setVisibility(View.VISIBLE);
			findViewById(R.id.ll9).setVisibility(View.VISIBLE);
			findViewById(R.id.ll2).setVisibility(View.GONE);
			findViewById(R.id.l7).setVisibility(View.GONE);
			findViewById(R.id.main_ck_jilu).setVisibility(View.VISIBLE);
			findViewById(R.id.main_ck_jilu).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
//					startActivity(new Intent(NewMainActivity.this, NewOutStorageActivity.class));
					startActivity(new Intent(NewMainActivity.this, ChuKuDetailActivity.class));
				}
			});

			findViewById(R.id.main_rz1).setVisibility(View.VISIBLE);
			findViewById(R.id.main_rz1).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					startActivity(new Intent(NewMainActivity.this, LogsActivity.class));
				}
			});
			findViewById(R.id.main_tf).setVisibility(View.GONE);
			findViewById(R.id.main_tf).setClickable(false);
			findViewById(R.id.main_edit).setVisibility(View.VISIBLE);
			findViewById(R.id.main_edit).setClickable(true);
			findViewById(R.id.main_hm).setClickable(false);
			findViewById(R.id.main_hh).setClickable(false);
//				findViewById(R.id.null_RL).setVisibility(View.VISIBLE);
		}else {
			findViewById(R.id.ll_gongchang).setVisibility(View.VISIBLE);
			findViewById(R.id.ll_jingxiangshang).setVisibility(View.GONE);
			findViewById(R.id.main_tf).setVisibility(View.GONE);
			findViewById(R.id.main_tf).setClickable(false);
			findViewById(R.id.ll2).setVisibility(View.GONE);
			findViewById(R.id.main_hh).setClickable(true);
			findViewById(R.id.l7).setVisibility(View.GONE);
			findViewById(R.id.main_hm).setVisibility(View.INVISIBLE);
			findViewById(R.id.chuku_jilu).setVisibility(View.VISIBLE);
			findViewById(R.id.chuku_jilu).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					startActivity(new Intent(NewMainActivity.this, ChuKuDetailActivity.class));
//					startActivity(new Intent(NewMainActivity.this, NewOutStorageActivity.class));
//					startActivity(new Intent(NewMainActivity.this, NewOutStorageActivity.class));
				}
			});

		}

		// RoleInfo roleInfo = loginResultInfo.getRoleinfo();
		// if (roleInfo == null) {
		// showFinishDialog();
		// } else {
		// if (roleInfo.getPlant() == 0) {
		// operation.setEnabled(false);
		// operation.setFocusable(false);
		// }
		// if (roleInfo.getInspection() == 0) {
		// spector.setEnabled(false);
		// spector.setFocusable(false);
		// }
		// // if (roleInfo.getSell() == 0) {
		// // supplyAndDemand.setEnabled(false);
		// // supplyAndDemand.setFocusable(false);
		// // }
		// // if (roleInfo.getActivate() == 0) {
		// // activate.setEnabled(false);
		// // activate.setFocusable(false);
		// // }
		// //
		// // if (roleInfo.getSupplydemand() == 0) {
		// // supplyAndDemand.setEnabled(false);
		// // supplyAndDemand.setFocusable(false);
		// // }
		// }

		//标签采集数据同步
		initDataSync();

		/**
		 * 生产信息
		 */
		operation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(NewMainActivity.this, NewOperationActivity.class);
				NewMainActivity.this.startActivity(intent);
			}
		});

		/**
		 * 巡检信息
		 */
		spector.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(MainActivity.this,
				// SpectorActivity.class);
				// startActivity(intent);
				// overridePendingTransition(R.anim.push_left_in,
				// R.anim.push_left_out);
				// Intent intent = new Intent(Intents.Scan.ACTION);
				// intent.putExtra("type", 2);
				// startActivityForResult(intent, 99);

				Intent intent = new Intent(NewMainActivity.this, NewSpectorActivity.class);
				NewMainActivity.this.startActivity(intent);
			}
		});

		// 销售
		sales.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(NewMainActivity.this,
				// SalesActivity.class);
				// startActivity(intent);
				Intent intent = new Intent(NewMainActivity.this, NewSalesActivity.class);
				startActivity(intent);
			}
		});

		// // 包装附码
		// activate.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(MainActivity.this,
		// ActivateActivity.class);
		// startActivity(intent);
		// overridePendingTransition(R.anim.push_left_in,
		// R.anim.push_left_out);
		// }
		// });
		//
		// supplyAndDemand.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(MainActivity.this,
		// SupplyMainActivity.class);
		// startActivity(intent);
		// overridePendingTransition(R.anim.push_left_in,
		// R.anim.push_left_out);
		// }
		// });

		exit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ShowLogoutDialog("退出当前帐号", "确定退出当前帐号吗？", "确定退出", "取消", null, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						try {
							Intent intent = new Intent(NewMainActivity.this, LoginActivity.class);
							startActivity(intent);
							NewMainActivity.this.finish();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		});

		// added on 20170109
		// 装箱
		findViewById(R.id.main_zx_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 直接跳转
				Intent intent = new Intent(NewMainActivity.this, PackActivity.class);
				// intent.putExtra(PalUtils.PACK_MODEL_ITT, boxBindCodeResult);
				intent.putExtra(PalUtils.PACK_TYPE_ITT, 1);
				// intent.putExtra(PalUtils.PACK_CODE_ITT, scanCode);
				startActivity(intent);
				// Intent intent = new Intent(Intents.Scan.ACTION);
				// startActivityForResult(intent, BOX_RQC);
			}
		});
		// 装盒
		findViewById(R.id.main_zh_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NewMainActivity.this, PackActivity.class);
				// intent.putExtra(PalUtils.PACK_MODEL_ITT, boxBindCodeResult1);
				intent.putExtra(PalUtils.PACK_TYPE_ITT, 2);
				// intent.putExtra(PalUtils.PACK_CODE_ITT, scanCode);
				startActivity(intent);
				// 直接跳转
				// Intent intent = new Intent(Intents.Scan.ACTION);
				// startActivityForResult(intent, GIFT_RQC);
			}
		});
		// 包装记录
		findViewById(R.id.main_bzjl_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(NewMainActivity.this, HistoryActivity.class));
			}
		});
		// 拆箱(拆盒)
//		findViewById(R.id.main_cx_rl).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(Intents.Scan.ACTION);
//				startActivityForResult(intent, UNPACK_RQC);
//			}
//		});
		// 经销商管理
		findViewById(R.id.main_jxsgl_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(NewMainActivity.this, DealerListActivity.class));
			}
		});
		// //////////////////////////////////////////
		// 仓库管理
		findViewById(R.id.main_ckgl_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(NewMainActivity.this, WarehouseListActivity.class));
			}
		});

		// 入库
//		findViewById(R.id.main_rk_rl).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				if (MyApplication.mSettings.getInt("usertype",0)== UserType._JING_XIAO_SHANG.getTypeID()){
//					startActivity(NewInStorageActivityTow.class);
//				}else {
//					startActivity(new Intent(NewMainActivity.this, NewInStorageActivity.class));
//				}
//			}
//		});

		// 出库
		findViewById(R.id.main_ck_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(NewMainActivity.this, NewOutStorageActivity.class));
			}
		});
		findViewById(R.id.chuku_jxs).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(NewMainActivity.this, NewOutStorageActivity.class));
			}
		});

		// 仓储
//		findViewById(R.id.main_cc_rl).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				startActivity(new Intent(NewMainActivity.this, NewInventoryActivity.class));
//			}
//		});
		findViewById(R.id.main_tf).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(OutStorageReturnActivity.class);
			}
		});
		findViewById(R.id.main_tf2).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(OutStorageReturnActivity.class);
			}
		});
		findViewById(R.id.main_tc_rl).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(TakeStorageActivity.class);
			}
		});
		initPopupWindow();
		setBtn = (ImageButton) findViewById(R.id.new_main_grzx_btn);
		setBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setPop.showAsDropDown(setBtn, 0, 0);
			}
		});
		//稽查
		findViewById(R.id.main_jc).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setJiCha();
//				startActivity(new Intent(NewMainActivity.this, LogsActivity.class));
			}
		});
		findViewById(R.id.main_jc1).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setJiCha();
			}
		});
		// 装垛
		findViewById(R.id.main_zhuangduo_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 直接跳转界面
				Intent intent = new Intent(NewMainActivity.this, CribActivity.class);
				startActivity(intent);
				// Intent intent = new Intent(Intents.Scan.ACTION);
				// startActivityForResult(intent, CRIB_RQC);
			}
		});

		// 标签采集
		findViewById(R.id.main_bqcj).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 直接跳转界面
				Intent intent = new Intent(NewMainActivity.this, NewCollectSelect.class);
				startActivity(intent);
			}
		});
		//经销商入库
		findViewById(R.id.main_jsrk).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(New_JX_Rk_Activity.class);
			}
		});

		//调换记录
		findViewById(R.id.main_dhjl).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(New_DH_LIst_Activity.class);
			}
		});

		//换货操作
		findViewById(R.id.main_edit).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(NewEditOrderActivity.class);
			}
		});
		//换货操作
		findViewById(R.id.main_hh).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(NewEditOrderActivity.class);
			}
		});
		//换货操作
		findViewById(R.id.main_hh1).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(NewEditOrderActivity.class);
			}
		});
		findViewById(R.id.main_hm).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(New_HM_Activity.class);
			}
		});
	}

	private void deleteMoreLogs() {
		String jaString = MyApplication.mSettings.getString(MyApplication.ALL_LOGS, "");
		try {
			JSONArray ja=null;
			if(StringUtils.isEmpty(jaString)){
				ja=new JSONArray();
			}else{
				ja=new JSONArray(jaString);

			}
			for (int i = 0; i < ja.length(); i++) {
				JSONObject jsonObject = ja.getJSONObject(i);
				String time = jsonObject.getString("time");
				boolean isDelete = Utils.isDelete(time);
				if(isDelete){
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
						ja.remove(i);
						i--;
					}

				}
			}
			MyApplication.editor.putString(MyApplication.ALL_LOGS,ja.toString());
			MyApplication.editor.commit();

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void setJiCha() {
		permissionUtil.setOnPerissionLisner(new PermissionUtil.OnPerissionListener() {
			@Override
			public void OnAllGetResult(List<String> perission_names) {
				startActivity(new Intent(NewMainActivity.this,JiChaActivity.class));
			}

			@Override
			public void OnThrough(List<String> perission_names) {

			}

			@Override
			public void OnError(List<String> perission_names) {

			}
		}).getPerission("提示","请赋予摄像头权限与定位权限！",
				PermissionUtil.Permission.CAMERA_PERMISSION.getValue(),
				PermissionUtil.Permission.ACCESS_COARSE_LOCATION_PERMISSION.getValue(),
				PermissionUtil.Permission.ACCESS_FINE_LOCATION_PERMISSION.getValue());
	}

	private void initDataSync() {
		GetbaseInfoRequest request = new GetbaseInfoRequest();
//		if (MyApplication.mSettings.getInt("usertype",0)!= UserType._JING_XIAO_SHANG.getTypeID()){
//			DataSyncTask dataSyncTask = new DataSyncTask();
//			dataSyncTask.execute(request);
//		}
	}

	/**
	 * 初始化PopupWindow
	 */
	private void initPopupWindow() {
		setPop = new PopupWindow(this);
		LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
		View conentView = inflater.inflate(R.layout.popup_dioag, null);
		int h = this.getWindowManager().getDefaultDisplay().getHeight();
		int w = this.getWindowManager().getDefaultDisplay().getWidth();
		// 设置SelectPicPopupWindow的View
		setPop.setContentView(conentView);
		// 设置SelectPicPopupWindow弹出窗体的宽
		setPop.setWidth(w / 2 + 50);
		// 设置SelectPicPopupWindow弹出窗体的高
		setPop.setHeight(LayoutParams.WRAP_CONTENT);
		// 设置SelectPicPopupWindow弹出窗体可点击
		setPop.setFocusable(true);
		setPop.setOutsideTouchable(true);
		// 刷新状态
		setPop.update();
		// 实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(0000000000);
		// 点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener ，设置其他控件变化等操作
		setPop.setBackgroundDrawable(dw);
		// mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
		// 设置SelectPicPopupWindow弹出窗体动画效果
		// this.setAnimationStyle(R.style.AnimationPreview);
		TextView userNameText = (TextView) conentView.findViewById(R.id.popup_user_name);
		userNameText.setText(MyApplication.mSettings.getString("username",""));

		conentView.findViewById(R.id.popup_xgmm).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(NewMainActivity.this, ChangePasswordActivity.class);
				NewMainActivity.this.startActivityForResult(intent,1000);
			}
		});
		conentView.findViewById(R.id.popup_zx).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				setPop.dismiss();
				MyApplication.editor.putString("token","");
				MyApplication.editor.commit();
				Intent intent = new Intent(NewMainActivity.this, LoginActivity.class);
				NewMainActivity.this.startActivity(intent);
				NewMainActivity.this.finish();
			}
		});
	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		permissionUtil.onRequestPermissionsResult(requestCode,permissions,grantResults);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 1000&&resultCode==1000) {
			//修改密码返回的
			setPop.dismiss();

		}
		if (resultCode == RESULT_OK) {

			if (requestCode == 100) {
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				// contents = Utils.getCodeStr(contents);

				CodeActivationInfo activationInfo = new CodeActivationInfo();
				activationInfo.setStartcode(contents);
				activationInfo.setEnterpriseid(enterpriseId);
				activationInfo.setIsnew(isNew);
				progressDialog = ProgressDialog.show(NewMainActivity.this, "提示", "正在查询....", true, false);
				PaimaAsyn paimaAsyn = new PaimaAsyn();
				paimaAsyn.execute(activationInfo);

			}

			if (requestCode == 99) {
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				contents = Utils.getCodeStr(contents);

				CodeActivationInfo activationInfo = new CodeActivationInfo();
				activationInfo.setStartcode(contents);
				activationInfo.setEnterpriseid(enterpriseId);
				activationInfo.setIsnew(isNew);
				progressDialog = ProgressDialog.show(NewMainActivity.this, "提示", "正在查询....", true, false);
				XJPaimaAsyn paimaAsyn = new XJPaimaAsyn();
				paimaAsyn.execute(activationInfo);
			}

			// added on 20170109
			// 箱码
			if (requestCode == BOX_RQC) {
				scanCode = Utils.getCodeStr(data.getStringExtra(Intents.Scan.RESULT).trim());
				requestPackScanCode(1, scanCode);
			}

			// 盒码
			if (requestCode == GIFT_RQC) {
				scanCode = Utils.getCodeStr(data.getStringExtra(Intents.Scan.RESULT).trim());
				requestPackScanCode(2, scanCode);
			}

			// 拆箱
			if (requestCode == UNPACK_RQC) {
				String contents = Utils.getCodeStr(data.getStringExtra(Intents.Scan.RESULT).trim());
				requestUnpackScanCode(contents);
			}

			// added on 20170331
			if (requestCode == CRIB_RQC) {
				scanCode = Utils.getCodeStr(data.getStringExtra(Intents.Scan.RESULT).trim());
				requestPackScanCode(3, scanCode);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void showFinishDialog() {
		new AlertDialog.Builder(NewMainActivity.this).setTitle("提示").setMessage("数据初始化失败").setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						NewMainActivity.this.finish();
					}
				}).create().show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			ShowExitActivityDialog("退出系统吗?");
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View view) {
		if(view.getId() == R.id.rizhi_main){
			startActivity(new Intent(NewMainActivity.this, LogsActivity.class));
		}
	}

	/**
	 * 生产信息交互
	 *
	 * @author Administrator
	 *
	 */
	private class PaimaAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(NewMainActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(NewMainActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {

					CodeActivationResultInfo codeActivationResultInfo = (CodeActivationResultInfo) Utils
							.fromJSON(string, CodeActivationResultInfo.class);

					if (codeActivationResultInfo.getResult() == 2010) {
						List<MaterialBatch> batches = codeActivationResultInfo.getBatchList();
						if (batches == null || batches.size() == 0) {
							Toast.makeText(NewMainActivity.this, "批次列表空", Toast.LENGTH_LONG).show();
							return;
						} else {
							try {
								OperationTypeDict operationType = codeActivationResultInfo.getOperationType();
								Intent intent = new Intent(NewMainActivity.this, NewOperationActivity.class);

								if (operationType == null) {
									intent.putExtra("typeId", -1);
									intent.putExtra("typeStr", "");
								} else {
									intent.putExtra("typeId", operationType.getOperationtypeid());
									intent.putExtra("typeStr", operationType.getOperationtype());
								}
								intent.putExtra("batches", string);
								startActivity(intent);
							} catch (Exception e) {
								// TODO: handle exception
								e.printStackTrace();
							}

						}
					} else {
						Toast.makeText(NewMainActivity.this, codeActivationResultInfo.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {

			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(2000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 巡检记录交互
	 *
	 * @author Administrator
	 *
	 */
	private class XJPaimaAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(NewMainActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(NewMainActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					CodeActivationResultInfo codeActivationResultInfo = (CodeActivationResultInfo) Utils
							.fromJSON(string, CodeActivationResultInfo.class);

					if (codeActivationResultInfo.getResult() == 3010) {
						List<MaterialBatch> batches = codeActivationResultInfo.getBatchList();
						if (batches == null || batches.size() == 0) {
							Toast.makeText(NewMainActivity.this, "批次列表空", Toast.LENGTH_LONG).show();
							return;
						} else {
							Intent intent = new Intent(NewMainActivity.this, SpectorActivity.class);
							// intent.putParcelableArrayListExtra("batches",
							// (ArrayList<? extends Parcelable>) batches);

							intent.putExtra("batches", string);
							startActivity(intent);
						}
					} else {
						Toast.makeText(NewMainActivity.this, codeActivationResultInfo.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(3000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 检测是否更新 异步
	 *
	 * @author Administrator
	 *
	 */
	public class UpdateAsync extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			/*
			 * 此方法在主线程执行，任务执行的结果作为此方法的参数返回
			 */
			if (res == null || res.equals("")) {
				Toast.makeText(NewMainActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				try {
					JSONObject jo = new JSONObject(res.toString());
					if (jo.getInt("code") != 200) {
						Toast.makeText(getApplicationContext(), jo.getString("msg"), Toast.LENGTH_LONG).show();
						return;
					}
					res = jo.getJSONObject("data").toString();
				} catch (Exception e) {
					res="";
				}
				if (res == null || res.equals("")) {
					Toast.makeText(NewMainActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG)
							.show();
				} else {
//					Type userListType = new TypeToken<Version>() {
//					}.getType();
					Version version = (Version) Utils.fromJSON(res.toString(), Version.class);
//					version = (Version) JsonUtils.fromJSON(res.toString(), userListType);
					upData(version);

				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {

			VersionClientInfo versioninfo = new VersionClientInfo();
			try {
				versioninfo.setVersioncode(Integer.parseInt(getString(R.string.version_code)));
			} catch (NumberFormatException efe) {
				versioninfo.setVersioncode(0);
			}
			versioninfo.setVersion(Utils.getVersionName(NewMainActivity.this));
			versioninfo.setType(1);
//			String json = Utils.toJSON(versioninfo);
//			int type = Utils.getTempValue(Temp.update);
			String result = Utils.postCommit(getString(R.string.first_url) + getString(R.string.isUpdateVersion),
					versioninfo);// 提交数据
			return result;
		}
	}

	private void upData(Version version) {
		String des = version.getDescribe();
		final String updateUrl = version.getUrl().trim();
		final int isforceupdate = version.getIsforceupdate();
		CharSequence charseq = null;
		if (!Utils.isEmpty(des)) {
			charseq = Html.fromHtml(des);
		}
		if (updateUrl.equals("0") || Utils.isEmpty(updateUrl)) {
			// SkipActivity(Main.this,true);
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(NewMainActivity.this);
			builder.setTitle("升级");
			if (charseq == null) {
				builder.setMessage(des);
			} else {
				builder.setMessage(charseq);
			}
			builder.setCancelable(false);// 是否可以按BACK键
			builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					GoToDown(updateUrl);
				}
			});
			if (isforceupdate!=1) // 非强制升级
			{
				builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// 初始化字典
					}
				});
			}
			builder.create().show();
		}
	}

	private void GoToDown(String versionUrl) {
		if (!versionUrl.contains(".apk")) {
			Toast.makeText(this, "下载地址错误！", Toast.LENGTH_SHORT).show();
			return;
		}
		final PopupWindowUtil util = new PopupWindowUtil(this);
		util.setContextView(R.layout.downloud_layout);
		util.setType(0, 0);
		TextView DT = (TextView) util.getView().findViewById(R.id.downLoadText);
		ProgressBar bar = (ProgressBar) util.getView().findViewById(R.id.downLoadBar);
		util.show(Gravity.BOTTOM, 0, 0);
		MyApplication.getInstance().Download(this, DT, bar, versionUrl, new HttpConnectService.UrlErrorLestener() {
			@Override
			public void ErrorMessage(HttpException errorException, String msg) {
				util.getPopupWindow().dismiss();
				Toast.makeText(NewMainActivity.this, "下载失败！", Toast.LENGTH_SHORT).show();
			}
		});
	}
	/**
	 * 获取扫码数据-装箱装盒
	 *
	 * @param flag
	 *            1 box 2 gift 3扫描垛位码信息
	 */
	private void requestPackScanCode(int flag, String scanCode) {
		if (PalUtils.isEmpty(scanCode)) {
			PalUtils.showShortToast(getApplicationContext(), getString(R.string.sales_msg_default_status));
			return;
		}
		progressDialog = ProgressDialog.show(NewMainActivity.this, "提示", "正在查询....", true, false);
		BoxBindCodeRequest boxBindCodeRequest = new BoxBindCodeRequest();
		boxBindCodeRequest.setEnterpriseId(enterpriseId);
		boxBindCodeRequest.setBoxCode(scanCode);
		String json = Utils.toJSON(boxBindCodeRequest);
		int magType = PalUtils.MsgType.BoxCode;
		InterActionModel interActionModel = new InterActionModel();
		switch (flag) {
			case 1:
				magType = PalUtils.MsgType.BoxCode;
				interActionModel.setIndex(BOX_RQT);
				break;
			case 2:
				interActionModel.setIndex(GIFT_RQT);
				magType = PalUtils.MsgType.PackCode;
			case 3:
				interActionModel.setIndex(CRIB_RQC);
				magType = PalUtils.MsgType.CribCode;
		}
		Message message = new Message(magType, PalUtils.ENCRYPT, json);
		interActionModel.setUrl(getString(R.string.first_url) + getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}

	/**
	 * 获取扫码数据-拆箱拆盒
	 *
	 *
	 */
	private void requestUnpackScanCode(String scanCode) {
		if (PalUtils.isEmpty(scanCode)) {
			PalUtils.showShortToast(getApplicationContext(), getString(R.string.sales_msg_default_status));
			return;
		}
		progressDialog = ProgressDialog.show(NewMainActivity.this, "提示", "正在查询....", true, false);
		SplitBoxGetCodeRequest boxBindCodeRequest = new SplitBoxGetCodeRequest();
		boxBindCodeRequest.setEnterpriseId(enterpriseId);
		boxBindCodeRequest.setCode(scanCode);
		String json = Utils.toJSON(boxBindCodeRequest);
		Message message = new Message(PalUtils.MsgType.SplitBoxGetCode, PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(UNPACK_RQT);
		interActionModel.setUrl(getString(R.string.first_url) + getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}

	@Override
	public void onResult(AsyncLoadListener asyncLoadListener, String response, int actionId) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
		if (PalUtils.isEmpty(response)) {
			PalUtils.showShortToast(getApplicationContext(), getString(R.string.server_error));
		} else {
			switch (actionId) {
				// 箱码
				case BOX_RQT:
					BoxBindCodeResult boxBindCodeResult = (BoxBindCodeResult) PalUtils.getPostResult(response,
							BoxBindCodeResult.class);
					if (boxBindCodeResult == null) {
						PalUtils.showShortToast(getApplicationContext(), getString(R.string.analyse_error));
					} else if (boxBindCodeResult.getResult() > 0) {
						Intent intent = new Intent(this, PackActivity.class);
						intent.putExtra(PalUtils.PACK_MODEL_ITT, boxBindCodeResult);
						intent.putExtra(PalUtils.PACK_TYPE_ITT, 1);
						intent.putExtra(PalUtils.PACK_CODE_ITT, scanCode);
						startActivity(intent);
					} else {
						PalUtils.showShortToast(getApplicationContext(), boxBindCodeResult.getResultinfo());
					}
					break;
				// 盒码
				case GIFT_RQT:
					BoxBindCodeResult boxBindCodeResult1 = (BoxBindCodeResult) PalUtils.getPostResult(response,
							BoxBindCodeResult.class);
					if (boxBindCodeResult1 == null) {
						PalUtils.showShortToast(getApplicationContext(), getString(R.string.analyse_error));
					} else if (boxBindCodeResult1.getResult() > 0) {
						Intent intent = new Intent(this, PackActivity.class);
						intent.putExtra(PalUtils.PACK_MODEL_ITT, boxBindCodeResult1);
						intent.putExtra(PalUtils.PACK_TYPE_ITT, 2);
						intent.putExtra(PalUtils.PACK_CODE_ITT, scanCode);
						startActivity(intent);
					} else {
						PalUtils.showShortToast(getApplicationContext(), boxBindCodeResult1.getResultinfo());
					}
					break;
				// 拆箱拆盒
				case UNPACK_RQT:
					SplitBoxGetCodeResult bindCodeRemoveResult = (SplitBoxGetCodeResult) PalUtils.getPostResult(response,
							SplitBoxGetCodeResult.class);
					if (bindCodeRemoveResult == null) {
						PalUtils.showShortToast(getApplicationContext(), getString(R.string.analyse_error));
					} else if (bindCodeRemoveResult.getResult() > 0) {
						Intent intent = new Intent(this, UnpackActivity.class);
						intent.putExtra(PalUtils.PACK_MODEL_ITT, bindCodeRemoveResult);
						startActivity(intent);
					} else {
						PalUtils.showShortToast(getApplicationContext(), bindCodeRemoveResult.getResultinfo());
					}
					break;
				// 装垛
				case CRIB_RQC:
					BoxBindCodeResult boxBindCodeResult2 = (BoxBindCodeResult) PalUtils.getPostResult(response,
							BoxBindCodeResult.class);
					if (boxBindCodeResult2 == null) {
						PalUtils.showShortToast(getApplicationContext(), getString(R.string.analyse_error));
					} else if (boxBindCodeResult2.getResult() > 0) {
						// Intent intent = new Intent(this, CribActivity.class);
						// intent.putExtra(PalUtils.PACK_MODEL_ITT,
						// boxBindCodeResult2);
						// intent.putExtra(PalUtils.PACK_TYPE_ITT, 2);
						// intent.putExtra(PalUtils.PACK_CODE_ITT, scanCode);
						// startActivity(intent);
					} else {
						PalUtils.showShortToast(getApplicationContext(), boxBindCodeResult2.getResultinfo());
					}
					break;
			}
		}
	}

	//数据同步异步任务
	class DataSyncTask extends MyAsyncTask {

		@Override
		protected Object doInBackground(Object... params) {
			GetbaseInfoRequest getbaseInfoRequest = (GetbaseInfoRequest) params[0];
			String json = Utils.toJSON(getbaseInfoRequest);
			com.gogowan.agroenterprise.model.Message message = new com.gogowan.agroenterprise.model.Message(31000, true,
					json);
			String res = Utils.postCommit(getString(R.string.first_url) + getString(R.string.first_url_page), message);
			return res;
		}

		@Override
		protected void onPostExecute(Object res) {
			if (isFinishing()) {
				return;
			}
			try {
				if (res == null || res.equals("")) {
					initError(getString(R.string.server_error));
				} else {
					com.gogowan.agroenterprise.model.Message message = (com.gogowan.agroenterprise.model.Message) Utils
							.fromJSON((String) res, com.gogowan.agroenterprise.model.Message.class);
					String string = Utils.getMessageContent(message);

					if (string == null || string.equals("")) {
						initError(getString(R.string.analyse_error));
					} else {
						GetbaseInfoResult getbaseInfoResult = (GetbaseInfoResult) Utils.fromJSON(string,
								GetbaseInfoResult.class);
						if (getbaseInfoResult.getResult() == 31000) {
							if (getbaseInfoResult.getMaterialInfo() != null
									&& getbaseInfoResult.getMaterialInfo().size() > 0) {
								dbHelper.initDataDictinary(getbaseInfoResult.getMaterialInfo());
								//initError(getbaseInfoResult.getResultinfo());
							}
						} else {
							initError(getbaseInfoResult.getResultinfo());
						}
					}
				}
			} catch (Exception ex) {
				initError(getString(R.string.analyse_error));
			}
			super.onPostExecute(res);
		}
	}



	private void initError(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		weakRefAsyncTask.cancel();
	}


}